package com.banciyuan.bcywebview.biz.main.discover.newestwork;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.novel.NovelAdapter;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.Novel;
import de.greenrobot.daoexample.model.TagDetail;

/**
 * Created by squall on 2017/5/23.
 */

public class NewestNovelWorkFragment extends BaseLazyContainerFragment {

    protected PullToRefreshListView refreshListView;
    private ListView mListView;
    protected ProgressbarHelper mProgressbarHelper;
    private List<Novel> nlist = new ArrayList<>();
    private NovelAdapter adapter;
    private int page = 1;
    private boolean loading = false;
    private boolean isEnd = false;
    private String url;
    private String mRankType;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.top_fragment_layout, container, false);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initAction();
        return rootView;
    }

    @Override
    protected void initArgs() {
        Bundle arguments = getArguments();
        mRankType = arguments.getString(gotoUtil.INTENT_VALUE_TWO);
        if (StringUtil.notNullEqual(mRankType, "fanfic")) {
            url = HttpUtils.BASE_URL + NovelApi.getAllfanfic();
        } else {
            url = HttpUtils.BASE_URL + NovelApi.getAllfiction();
        }
    }

    @Override
    public void fetchData() {
        loading = false;
        isEnd = false;
        page = 1;
        initData();
    }


    @Override
    protected void initProgressbar(View rootview) {
        View mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                if (!loading) {
                    loading = true;
                    mProgressbarHelper.onLoading();
                    isEnd = false;
                    page = 1;
                    initData();
                }
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootview) {
        refreshListView = (PullToRefreshListView) rootview.findViewById(R.id.top_refresh_lv);
        mListView = refreshListView.getRefreshableView();
    }

    @Override
    protected void initAction() {
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loading = false;
                isEnd = false;
                page = 1;
                initData();
            }
        });

        refreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading && !isEnd) {
                    loading = true;
                    page++;
                    initData();
                }
            }
        });
    }

    @Override
    protected void initData() {
        loading = true;
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.PAGE, page + ""));
        Map<String, String> map = HttpUtils.getData(paramsList);
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray reData = jsonObject.getJSONArray(HttpUtils.UPLOAD_DATA);
                        List<Novel> tempCardList = gson.fromJson(reData.toString(), new TypeToken<List<Novel>>() {
                        }.getType());
                        setWorkToTag(tempCardList);
                        processData(tempCardList);
                        onSuccess();
                    }
                } catch (Exception e) {
                    onError();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                onError();
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSuccess, url, getActivity(), map);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, map, onSuccess, errorProxy);
        VolleyQueue.getRquest(getActivity()).add(getUserdataRequest);
    }

    private void onSuccess() {
        mProgressbarHelper.onSuccess();
        refreshListView.onRefreshComplete();
        loading = false;
    }

    private void onError() {
        loading = false;
        mProgressbarHelper.onFailed();
        refreshListView.onRefreshComplete();
    }

    private void setWorkToTag(List<Novel> tempCardList) {
        for (Novel n : tempCardList) {
            if (!TextUtils.isEmpty(n.getWork())) {
                TagDetail tagDetail = new TagDetail();
                tagDetail.setWork(n.getWork());
                tagDetail.setTag_name(n.getWork());
                tagDetail.setWid(n.getWid());
                n.getPost_tags().add(0, tagDetail);
            }
        }
    }

    private void processData(List<Novel> tempCardList) {
        if (tempCardList.isEmpty())
            isEnd = true;
        if (page == 1)
            nlist.clear();
        nlist.addAll(tempCardList);
        if (null == adapter) {
            adapter = new NovelAdapter(getActivity(), nlist);
            mListView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }
}
